package com.sample.client.vm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sample.client.data.ResponseData
import com.sample.client.repo.BaseRepoImpl
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

open class BaseViewModel<T : BaseRepoImpl<*>>(repoImpl: T) : ViewModel() {
    private var viewModelJob: Job? = null
    protected val repo = repoImpl

    protected fun <T> viewModelLaunch(
        block: suspend () -> T?,
        callback: (result: ResponseData<T?>) -> Unit
    ) {
        viewModelJob = viewModelScope.launch {
            callback.invoke(repo.loadRequest(2, block))
        }
    }

    fun reload() {
        repo.updateConfig()
    }

    fun cancel() {
        cancelVmJob()
    }

    private fun cancelVmJob() {
        viewModelJob?.let {
            if (it.isActive && !it.isCancelled)
                it.cancel()
        }
    }

    override fun onCleared() {
        super.onCleared()
        cancel()
    }
}